package com.hitalkie.teacher.app;

import android.app.Application;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.hitalkie.teacher.BuildConfig;
import com.hitalkie.teacher.tx.InitBusinessHelper;
import com.hitalkie.teacher.util.PreferencesController;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import java.util.Locale;

/**
 * Date 24/09/2016
 *
 * @author charliema
 */

public class TalkieApplication extends Application {

    public static TalkieApplication sInstance;

    static boolean IS_DEBUG = BuildConfig.DEBUG;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;

        initPreferencesController();
        initPicasso();
        InitBusinessHelper.initApp(getApplicationContext());

        TalkieApplication.setLocale(TalkieApplication.getLocale());
        initKedaxunfei();
        initUmengPush();
    }

    private void initKedaxunfei() {
        // 将“12345678”替换成您申请的APPID，申请地址：http://open.voicecloud.cn
        SpeechUtility.createUtility(getApplicationContext(), SpeechConstant.APPID +"=58afbcce");
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        sInstance = null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        TalkieApplication.setLocale(TalkieApplication.getLocale());
    }

    private void initPicasso() {

    }

    private void initPreferencesController() {
        PreferencesController.init(getApplicationContext());
    }

    private void initUmengPush() {
        PushAgent pushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        pushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.e("Umeng Register:", "Umeng push device token:" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("Umeng Register fail:", s+ "    " + s1);

            }
        });
        pushAgent.setDebugMode(true);

        // 通知打开动作自定义
//        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
//            @Override
//            public void dealWithCustomAction(Context context, UMessage msg) {
//                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
//            }
//        };
//        pushAgent.setNotificationClickHandler(notificationClickHandler);

//        // 通知样式自定义
//        UmengMessageHandler messageHandler = new UmengMessageHandler() {
//            @Override
//            public Notification getNotification(Context context, UMessage msg) {
//               ／／ msg.builder_id是服务器下发的消息字段，用来指定通知消息的样式。开发者可在【友盟+】Push网站上指定，默认值为0。
//              switch (msg.builder_id) {
//                    case 1:
//                        Notification.Builder builder = new Notification.Builder(context);
//                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
//                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
//                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
//                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
//                        myNotificationView.setImageViewResource(R.id.notification_small_icon,  getSmallIconId(context, msg));
//                        builder.setContent(myNotificationView)
//                                .setSmallIcon(getSmallIconId(context, msg))
//                                .setTicker(msg.ticker)
//                                .setAutoCancel(true);
//
//                        return builder.getNotification();
//                    default:
//                        //默认为0，若填写的builder_id并不存在，也使用默认。
//                        return super.getNotification(context, msg);
//                }
//            }
//        };
//        pushAgent.setMessageHandler(messageHandler);

//        // 设置通知免打扰时间：
//        pushAgent.setNoDisturbMode(23, 0, 7, 0);
//        // 可以通过下面的设置，来关闭免打扰模式：
//        pushAgent.setNoDisturbMode(0, 0, 0, 0);


        // 应用在前台时，是否显示通知
//        pushAgent.setNotificaitonOnForeground(false);


//        // 自定义消息的处理
//        UmengMessageHandler messageHandler = new UmengMessageHandler(){
//            @Override
//            public void dealWithCustomMessage(final Context context, final UMessage msg) {
//                new Handler(getMainLooper()).post(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        // 对于自定义消息，PushSDK默认只统计送达。若开发者需要统计点击和忽略，则需手动调用统计方法。
//                        boolean isClickOrDismissed = true;
//                        if(isClickOrDismissed) {
//                            //自定义消息的点击统计
//                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
//                        } else {
//                            //自定义消息的忽略统计
//                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
//                        }
//                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
//                    }
//                });
//            }
//        };
//        pushAgent.setMessageHandler(messageHandler);

//        // 关闭推送
//        pushAgent.disable(new IUmengCallback() {
//            @Override
//            public void onSuccess() {
//            }
//
//            @Override
//            public void onFailure(String s, String s1) {
//            }
//        });
//        // 若调用关闭推送后，想要再次开启推送，则需要调用以下代码（请在Activity内调用）：
//        pushAgent.enable(new IUmengCallback() {
//            @Override
//            public void onSuccess() {
//            }
//
//            @Override
//            public void onFailure(String s, String s1) {
//            }
//        });


    }

    //------- sign in --------//
    public static void signIn(String token, long userId, int userType) {
        PreferencesController.getInstance().setString("token", token);
        PreferencesController.getInstance().setString("user_id", "" + userId);
        // 1.学生 2.外教 3.中教 4.staff 5.admin
        PreferencesController.getInstance().setInt("user_type", userType);
    }

    public static void signOut() {
        PreferencesController.getInstance().setString("token", "");
    }

    public static boolean isSignIn() {
        return !TextUtils.isEmpty(PreferencesController.getInstance().getString("token"));
    }

    public static String getToken() {
        return PreferencesController.getInstance().getString("token");
    }

    public static long getUserId() {
        String userId = PreferencesController.getInstance().getString("user_id");
        return Long.parseLong(userId);
    }

    public static int getUserType() {
        return PreferencesController.getInstance().getInt("user_type");
    }

    public static String getLanguage() {
        return PreferencesController.getInstance().getString("language");
    }

    // -------------------//
    public static java.util.Locale getLocale() {
        String language = getLanguage();
        switch (language) {
            case "zh":
                return Locale.CHINESE;
            case "en":
                return Locale.ENGLISH;
            default:
                return Locale.ENGLISH;
        }
    }

    public static void setLocale(java.util.Locale locale) {

        Resources resources = sInstance.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        config.locale = locale;
        resources.updateConfiguration(config, dm);

        // 存储
        if (locale.equals(Locale.CHINESE)) {
            PreferencesController.getInstance().setString("language", "zh");
        } else if (locale.equals(Locale.ENGLISH)) {
            PreferencesController.getInstance().setString("language", "en");
        }


    }


}
